import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_animate/flutter_animate.dart';
import 'package:get/get.dart';
import 'package:ball_lion/utils/date_time_utils.dart';
import 'package:ball_lion/utils/widget_utils.dart';
import 'package:ball_lion/module/match/match_support_widget.dart';
import 'package:ball_lion/widgets/card.dart';

import 'package:ball_lion/module/match/list/match_page_logic.dart';
import 'package:ball_lion/module/match/list/zq_focus_logic.dart';
import 'package:ball_lion/entity/match/zq_list_entity.dart';
import 'package:ball_lion/resources/colours.dart';
import 'package:ball_lion/resources/styles.dart';
import 'package:ball_lion/routes/routes.dart';
import 'package:ball_lion/utils/user.dart';
import 'package:ball_lion/utils/utils.dart';
import 'package:ball_lion/widgets/base/wqs_text.dart';
import 'package:ball_lion/widgets/circular.dart';
import 'package:ball_lion/widgets/count_down_text.dart';
import 'package:ball_lion/widgets/gif.dart';

class ZqListHotCell extends StatefulWidget {
  final ZqListEntity match;
  final MatchListProvider logic;
  const ZqListHotCell(this.match, this.logic, {super.key});

  @override
  State<ZqListHotCell> createState() => _ZqListHotCellState();
}

class _ZqListHotCellState extends State<ZqListHotCell> {
  @override
  Widget build(BuildContext context) {
    var details = <String>[];
    if (widget.match.homeScoreHalf != null &&
        widget.match.guestScoreHalf != null) {
      details.add(
          "半场${widget.match.homeScoreHalf}-${widget.match.guestScoreHalf}");
    }
    // if (widget.match.homeScore90 != null && widget.match.guestScore90 != null) {
    //   details.add("全场${widget.match.homeScore90}-${widget.match.guestScore90}");
    // }
    if (widget.match.homeScoreOt != null && widget.match.guestScoreOt != null) {
      details.add("加时${widget.match.homeScoreOt}-${widget.match.guestScoreOt}");
    }
    if (widget.match.homeScorePk != null && widget.match.guestScorePk != null) {
      details.add("点球${widget.match.homeScorePk}-${widget.match.guestScorePk}");
    }
    final detailTexts = <Widget>[];
    for (var i = 0; i < details.length; i += 1) {
      if (i + 1 < details.length && i != 0) {
        detailTexts.add(QsText(
          "${details[i]} ${details[i + 1]}",
        ));
        i += 1;
      } else {
        detailTexts.add(QsText(details[i]));
      }
    }
    final content = Container(
        height: 218,
        // padding: EdgeInsets.only(top: 44),
        decoration: BoxDecoration(
            image: DecorationImage(
                image: AssetImage(Utils.getImgPath('zq_detail_header.png')),
                fit: BoxFit.fitWidth)),
        // color: Colours.blue2766D6,
        child: Column(
          children: [
            Container(
              padding: EdgeInsets.symmetric(horizontal: 12),
              height: 44,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  GestureDetector(
                      onTap: () async {
                        if (User.isFollow(widget.match.id!)) {
                          Utils.onEvent('bspdzq', params: {'bspdzq': '7'});
                          await User.unFollow(widget.match.id!);
                        } else {
                          Utils.onEvent('bspdzq', params: {'bspdzq': '9'});
                          await User.follow(widget.match.id!);
                        }
                        setState(() {});
                        try {
                          Get.find<ZqFocusLogic>().getMatch();
                        } catch (e) {}
                        // matchInterestController.getMatch();
                      },
                      child: Container(
                        padding: const EdgeInsets.symmetric(vertical: 4),
                        // margin: EdgeInsets.only(left: 8),
                        child: User.isFollow(widget.match.id!)
                            ? Image.asset(
                                Utils.getImgPath("collection_red.png"),
                                color: Colours.white,
                                width: 18)
                            : Image.asset(Utils.getImgPath("collection.png"),
                                color: Colors.white, width: 18),
                      )),
                  QsText(widget.match.leagueName, fontSize: 14),
                  GestureDetector(
                    onTap: () {
                      User.closeHotMatch.add(widget.match.id!);
                      widget.match.isClose = true;
                      widget.logic.updateView();
                    },
                    child: Image.asset(
                      Utils.getImgPath('arrow_up.png'),
                      color: Colors.white,
                      width: 20,
                    ),
                  )
                ],
              ),
            ),
            Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Expanded(
                    child: _teamCol(
                        widget.match.homeLogo ?? "",
                        widget.match.homeName ?? "",
                        widget.match.homeRanking,
                        0,
                        2)),
                Column(
                  mainAxisSize: MainAxisSize.max,
                  children: [
                    const SizedBox(height: 20),
                    matchStatusWidget(),
                    const SizedBox(height: 6),
                    if (widget.match.status == '1' &&
                        (widget.match.matchTime.time
                                    ?.difference(DateTime.now())
                                    .inHours ??
                                0) <=
                            24 &&
                        (widget.match.matchTime.time
                                    ?.difference(DateTime.now())
                                    .inHours ??
                                0) >
                            0) ...[
                      CountDownText.toStart(
                        startTime: widget.match.matchTime!,
                        textStyle: const TextStyle(
                            fontSize: 22,
                            fontFamily: "Din",
                            fontWeight: FontWeight.w500),
                      ),
                      const QsText("距比赛开始", fontSize: 12, color: Colours.white)
                    ] else
                      QsText(
                        ((widget.match.homeScore90 != null &&
                                widget.match.guestScore90 != null)
                            ? "${widget.match.homeScore90}-${widget.match.guestScore90}"
                            : 'VS'),
                        fontSize: 22,
                        fontFamily: 'DIN',
                        maxLines: 1,
                      ),
                    const SizedBox(height: 6),
                    ConstrainedBox(
                      constraints: BoxConstraints(
                        minHeight: 30,
                      ),
                      child: DefaultTextStyle(
                        style: const TextStyle(fontSize: 12, height: 1.5),
                        maxLines: 1,
                        child: Column(
                            mainAxisAlignment: MainAxisAlignment.start,
                            crossAxisAlignment: CrossAxisAlignment.center,
                            children: detailTexts),
                      ),
                    ),
                    SizedBox(height: 15),
                    if (widget.match.hotAom == true ||
                        widget.match.hotVideo == true)
                      Circular(
                          radius: 10,
                          color: Colours.black.withOpacity(0.15),
                          height: 20,
                          padding: const EdgeInsets.symmetric(horizontal: 8),
                          child: Row(
                            mainAxisSize: MainAxisSize.min,
                            children: <Widget>[
                              if (widget.match.hotVideo == true)
                                GestureDetector(
                                  onTap: () => onTapLive(),
                                  child: Row(
                                    mainAxisSize: MainAxisSize.min,
                                    children: [
                                      if (widget.match.live == true)
                                        const GifWidget(
                                            width: 14,
                                            height: 14,
                                            asset: "in_live.gif",
                                            duration:
                                                Duration(milliseconds: 500))
                                      else
                                        Image.asset(
                                          Utils.getImgPath(
                                              "live_video_border.png"),
                                          width: 14,
                                        ),
                                      const SizedBox(width: 2),
                                      const QsText("视频直播",
                                          fontSize: 12, color: Colours.white)
                                    ],
                                  ),
                                ),
                              if (widget.match.hotAom == true &&
                                  widget.match.hotVideo == true)
                                const QsText("  |  ",
                                    fontSize: 12, color: Colours.white),
                              if (widget.match.hotAom == true)
                                GestureDetector(
                                  onTap: () => onTapAnimate(),
                                  child: Row(
                                    mainAxisSize: MainAxisSize.min,
                                    children: [
                                      Image.asset(
                                        Utils.getImgPath(
                                            "live_animation_border.png"),
                                        width: 14,
                                      ),
                                      const SizedBox(width: 2),
                                      const QsText("动画直播",
                                          fontSize: 12, color: Colours.white)
                                    ],
                                  ),
                                )
                            ],
                          )),
                    // const SizedBox(height: 15)
                  ],
                ).sized(width: 162),
                Expanded(
                    child: _teamCol(
                        widget.match.guestLogo ?? "",
                        widget.match.guestName ?? "",
                        widget.match.guestRanking,
                        0,
                        3)),
              ],
            ),
          ],
        ));
    return Block(
      cardStyle: CardStyle(
          margin: EdgeInsets.only(
              bottom: widget.match.lastMatchInDay ? 0 : 8,
              left: 8,
              right: 8,
              top: widget.match.needTopSpace ? 8 : 0)),
      child: DefaultTextStyle(
          style: const TextStyle(color: Colors.white, fontSize: 14),
          child: GestureDetector(
              onTap: () {
                Get.toNamed(Routes.zqMatchDetail, arguments: widget.match.id);
              },
              child: Stack(
                children: [
                  content,
                  Positioned(
                      left: 0,
                      right: 0,
                      bottom: 0,
                      child: SizedBox(
                        height: 22,
                        child: MatchSupportWidget(
                            widget.match.homeInter ?? '0',
                            widget.match.guestInter ?? '0',
                            widget.match.homeInterCount ?? 0,
                            widget.match.guestInterCount ?? 0,
                            widget.match.isInter ?? false,
                            widget.match.id!,
                            widget.match.homeId ?? 0,
                            widget.match.guestId ?? 0),
                      ))
                ],
              ))),
    );
  }

  Widget matchStatusWidget() {
    if (widget.match.status == '1') {
      return Container(
        height: 20,
        // width: 42,
        padding: EdgeInsets.symmetric(horizontal: 8),
        // alignment: Alignment.center,
        decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(10),
            color: Colours.black.withOpacity(0.15)),
        child: QsText(
            DateTimeUtils.formatDateString(
                widget.match.matchTime!, 'MM-dd HH:mm'),
            fontSize: 13),
      );
    } else if (widget.match.status == '2' ||
        widget.match.status == '3' ||
        widget.match.status == '4' ||
        widget.match.status == '5' ||
        widget.match.status == '6') {
      return Container(
        height: 20,
        padding: EdgeInsets.symmetric(horizontal: 12),
        // alignment: Alignment.center,
        decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(10),
            color: Colours.black.withOpacity(0.15)),
        child: widget.match.status != '3'
            ? Wrap(
                children: [
                  QsText(widget.match.show?.replaceAll("'", "") ?? "",
                      color: Colors.white, fontSize: 12),
                  const QsText("'", color: Colors.white, fontSize: 12)
                      .animate(onPlay: (controller) => controller.repeat())
                      .fade(duration: 1000.ms)
                ],
              )
            : QsText(widget.match.show ?? "", fontSize: 13),
      );
    } else {
      return Container(
        height: 20,
        padding: EdgeInsets.symmetric(horizontal: 12),
        // alignment: Alignment.center,
        decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(10),
            color: Colours.black.withOpacity(0.15)),
        child: QsText(widget.match.show ?? "", fontSize: 13),
      );
    }
  }

  _teamCol(String logo, String name, String? rank, int id, int type) {
    return Column(
      children: [
        const SizedBox(height: 25),
        logo.length == 0
            ? Styles.placeholderIcon(width: 54, height: 54)
            : CachedNetworkImage(
                imageUrl: logo,
                // width: 50,
                height: 50,
                fit: BoxFit.cover,
                placeholder: (context, url) =>
                    Styles.placeholderIcon(width: 50),
                errorWidget: (context, url, error) => Image.asset(
                  Utils.getImgPath("zq_placeholder.png"),
                  fit: BoxFit.cover,
                ),
              ),
        const SizedBox(height: 5),
        QsText(name, maxLines: 1, fontWeight: FontWeight.w500),
        QsText(rank?.isEmpty ?? true ? "" : "[${rank ?? ""}]",
            fontSize: 11, color: Colours.white.withOpacity(0.6))
      ],
    );
  }

  onTapLive() {
    Get.toNamed(Routes.zqMatchDetail,
        arguments: widget.match.id, parameters: {"hotLive": "1"});
  }

  onTapAnimate() {
    Get.toNamed(Routes.zqMatchDetail,
        arguments: widget.match.id, parameters: {"hotAnimate": "1"});
  }
}
